<template>
    <div class="saerch-line">
        <el-input style="width:200px" v-model="searchValue" placeholder="请输入标题/专辑/作者" />
        <el-button type="primary" size="default" @click="getList">
            <i class="iconfont icon-sousuo"></i>
            搜索
        </el-button>
        <el-button type="primary" @click="openDialog">
            <i style="font-size: 26px;">+</i>
            添加</el-button>
    </div>
    <div class="tab-container">
        <el-table :data="list" style="width: 100%;" height="460" border>
            <el-table-column align="center" fixed label="编号" prop="id" width="60" />
            <el-table-column align="center" label="封面" prop="poster" width="120">
                <template #default="scope">
                    <img :src="scope.row.img.startsWith('http') ? scope.row.img : 'http://tmp00002.learv.com/' + scope.row.img"
                        width="40" height="40" alt="" />
                </template>
            </el-table-column>
            <el-table-column align="center" label="标题" prop="title" width="200" />
            <el-table-column align="center" label="作者" prop="author" width="200" />
            <el-table-column align="center" label="专辑" prop="album" width="200" />
            <el-table-column align="center" label="时长/秒" prop="time" width="200" />
            <el-table-column align="center" label="歌词" prop="lrc" width="60">
                <template #default="scope">
                    <el-tag v-if="scope.row.lrc" type="success" size="default">是</el-tag>
                    <el-tag v-else type="info" size="default">否</el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" label="播放" width="260">
                <template #default="scope">
                    <audio :src="scope.row.src" controls style="height: 35px;"></audio>
                </template>
            </el-table-column>

            <el-table-column align="center" fixed="right" label="操作" width="80">
                <template #default="scope">
                    <el-button type="danger" size="small" @click.prevent="deleteRow(scope.$index)">
                        <i class="iconfont icon-shanchu"></i>
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 40]" :small="small" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
    <el-dialog v-model="dialogVisible" title="音乐添加" :width="srceenWidth" :before-close="handleClose">
        <el-form :model="form" label-width="120px">
            <el-form-item label="封面">
                <Upload @uploadEvt="getAvatar" propsSize="100px" />
            </el-form-item>
            <el-form-item label="标题">
                <el-input v-model="form.title" placeholder="请输入标题" required />
            </el-form-item>
            <el-form-item label="作者">
                <el-input v-model="form.author" placeholder="请输入作者" />
            </el-form-item>
            <el-form-item label="专辑">
                <el-input v-model="form.tel" placeholder="请输入专辑" />
            </el-form-item>
            <el-form-item label="时长/秒">
                <el-input v-model="form.description" />
            </el-form-item>
            <el-form-item label="音乐">
                <el-upload v-model="form.src" class="upload-demo" :show-file-list="false"
                    action="http://123.56.141.187:82/ftyyptapi/upload/create" :headers="{
                        // token:localStorage.getItem('token'),
                        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJpYXQiOjE3NTUzMTU4Nzd9.47ZOzCZskK2VgG3w54BPtrCgyLLNR-uqRo3k8L8-4KQ'
                    }" :on-success="handleUploadSuccess">
                    <el-button type="primary">上传附件</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item label="试听">
                <audio @error="handleAudioError" :src="preview" :key="preview" controls style="height: 35px;"
                    ref="audioRef"></audio>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="add">
                    立即创建
                </el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref, watch } from 'vue'
import { requestIns } from '@/utils/request'
import { ElMessage } from 'element-plus'
import Upload from '@/components/common/Upload.vue'


const dialogVisible = ref(false)
const srceenWidth = ref('50%')
const list = ref([])
const total = ref(0)
const searchValue = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const preview = ref('http://tmp00002.learv.com/mp3/dengziqi_001ZKGzl4OtmrJ.m4a')
const form = reactive({
    img: '',
    src: '',
    title: '',
    author: '',
    album: '',
    time: 0
})
onMounted(() => {
    getList()
    changeWidth()
})
window.addEventListener('resize', () => {
    changeWidth()
})
const getAvatar = (poster) => {
    form.img = poster
}
const audioRef = ref(null)
const handleAudioError = (e) => {
    console.error('音频播放错误:', e)
    ElMessage.error('无法播放音频，请检查文件或 URL')
}
const handleUploadSuccess = (
    response,
    uploadFile
) => {
    console.log('上传成功', response, '文件', uploadFile)
    form.src = response.data.database
    preview.value = ''
    nextTick(() => {
        preview.value = response.data.preview + '?t=' + new Date().getTime()
        console.log('预览 URL:', preview.value);
        if (audioRef.value) {
            audioRef.value.load();
            console.log('音频加载触发');
        } else {
            console.error('音频引用不可用');
        }
    })

}

const changeWidth = () => {
    if (window.innerWidth < 1000) {
        srceenWidth.value = '90%'
    } else {
        srceenWidth.value = '50%'
    }
}

const getList = async () => {
    const res = await requestIns.request('/fsdy/music/index', 'get', {
        pagenum: currentPage.value,
        pagesize: pageSize.value,
    })
    console.log(res)
    if (res.state = 200) {
        list.value = res.list
        total.value = res.total
    }
}
const deleteRow = async (index) => {
    const item = list.value.find((item, idx) => idx == index)
    console.log(item.id)
    const res = await requestIns.request('/fsdy/music/delete', 'delete', {
        id: item.id
    })
    console.log(res)
    if (res.state === 200) {
        getList()
        ElMessage.success('删除成功')
    }
}
const openDialog = () => {
    dialogVisible.value = true
}


const add = async () => {

    const res = await requestIns.request('/fsdy/music/create', 'post', {
        ...form
    }, {
        'Content-Type': 'application/x-www-form-urlencoded'
    })
    console.log(res)
    if (res.state == 201) {
        getList()
        ElMessage.success('添加成功')
    }
    dialogVisible.value = false
}

const handleSizeChange = (val) => {
    currentPage.value = 1
    pageSize.value = val
    getList()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getList()
}
const handleClose = (done) => {
    done()
}
</script>

<style scoped lang="scss">
.saerch-line {
    background-color: #fff;
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    margin-bottom: 20px;
    display: flex;
    align-items: center;

    .el-input {
        width: 300px;
        margin-left: 20px;
        margin-right: 40px;
    }
}

.tab-container {
    background-color: #fff;
    width: 100%;
    padding: 20px;
    box-sizing: border-box;

    .btn {
        padding-bottom: 15px;
    }
}

.demo-pagination-block {
    margin-top: 10px;
    width: 100%;
    display: flex;
    justify-content: center;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}


.actorsBox {
    ::v-deep(.el-form-item__content) {
        gap: 10px;
        display: flex;
    }

    .addActor {
        display: block;
        height: 130px;

    }
}
</style>